package Gui.Dialogs;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FontMetrics;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Gui.GameFrame;
import Main.Defines;

public class AskForLoanDialog extends JDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4100045234785802418L;
	private boolean m_dialogClosed;
	private boolean m_playerWantedLoan;
	private JPanel jp;
	
	public boolean isClosed() {
		return m_dialogClosed;
	}

	public boolean isLoanOK() {
		return m_playerWantedLoan;
	}

	public void buildUIContents(final int playerNumber, int moneyNeeded, String reason,  int loan) {
		m_dialogClosed = false;

		JLabel info = new JLabel();
		info
				.setText(String
						.format(
								"<html>Player %d needs <br> $%d %s <br><br>Does he/she want to take out a $%d loan?<br><br>",
								playerNumber + Defines.PRINTABLE_PLAYER_ID_OFFSET, moneyNeeded, reason, loan)); 
		
		JPanel buttonPanel = new JPanel();
		JButton yes = new JButton("Yes");
		yes.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				m_playerWantedLoan = true;
				m_dialogClosed = true;
				dispose();
			}
		});
		buttonPanel.add(yes);
		JButton no = new JButton("No");
		no.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				m_playerWantedLoan = false;
				m_dialogClosed = true;
				dispose();

			}
		});
		buttonPanel.add(no);
		jp.add(info, BorderLayout.CENTER);
		jp.add(buttonPanel, BorderLayout.SOUTH);

	}
	
	public AskForLoanDialog(int playerNumber, int moneyNeeded, String reason, int loan) {
		//super(GameFrame.getInstance(), String.format("Player %d needs $%d!",playerNumber+1, moneyNeeded), true);
		setModalityType(getModalityType().APPLICATION_MODAL);
		setLayout(new BorderLayout());
		jp = new JPanel();
		jp.setLayout(new BorderLayout());
		jp.setBorder(Defines.getEmptyBorderConstraints()); 
		
		buildUIContents(playerNumber, moneyNeeded, reason, loan);
		add(jp, BorderLayout.CENTER);
		
		m_playerWantedLoan = false;
		pack();
		
		if (getTitle() != null) {
			FontMetrics fm = getFontMetrics(getFont());
			int width = fm.stringWidth(getTitle()) + Defines.ICON_WIDTH; 
			width = (int) Math.max(width, getPreferredSize().getWidth());
			setSize(new Dimension(width, getHeight()));
		}
		setLocationRelativeTo(GameFrame.getInstance());
		setVisible(true);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

	}
}
